<?php

namespace common\models\c2\entity;

use backend\models\c2\entity\rbac\BeUser;
use common\helpers\CodeGenerator;
use common\models\c2\statics\AmoebaFormType;
use common\models\c2\statics\AmoebaState;
use common\models\c2\statics\AmoebaType;
use cza\base\models\statics\EntityModelStatus;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * This is the model class for table "{{%amoeba}}".
 *
 * @property string $id
 * @property integer $type
 * @property string $attributeset_id
 * @property string $province_id
 * @property string $city_id
 * @property string $district_id
 * @property string $code
 * @property string $name
 * @property string $label
 * @property string $seo_code
 * @property string $geo_longitude
 * @property string $geo_latitude
 * @property string $geo_marker_color
 * @property string $created_by
 * @property string $updated_by
 * @property integer $state
 * @property integer $status
 * @property integer $position
 * @property string $created_at
 * @property string $updated_at
 */
class Amoeba extends \cza\base\models\ActiveRecord
{
    /**
     * @var AmoebaFormItem
     */
    public $amoebaForms;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%amoeba}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['attributeset_id', 'province_id', 'city_id', 'district_id', 'created_by', 'updated_by',
                'position'], 'integer'],
            [['name'], 'required'],
            [['created_at', 'updated_at'], 'safe'],
            [['type', 'state', 'status'], 'integer', 'max' => 4],
            [['code', 'label', 'seo_code', 'geo_longitude', 'geo_latitude', 'geo_marker_color',
                'name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'type' => Yii::t('app.c2', 'Type'),
            'attributeset_id' => Yii::t('app.c2', 'Attributeset ID'),
            'province_id' => Yii::t('app.c2', 'Province ID'),
            'city_id' => Yii::t('app.c2', 'City ID'),
            'district_id' => Yii::t('app.c2', 'District ID'),
            'code' => Yii::t('app.c2', 'Code'),
            'label' => Yii::t('app.c2', 'Label'),
            'name' => Yii::t('app.c2', 'Name'),
            'seo_code' => Yii::t('app.c2', 'Seo Code'),
            'geo_longitude' => Yii::t('app.c2', 'Geo Longitude'),
            'geo_latitude' => Yii::t('app.c2', 'Geo Latitude'),
            'geo_marker_color' => Yii::t('app.c2', 'Geo Marker Color'),
            'created_by' => Yii::t('app.c2', 'Created By'),
            'updated_by' => Yii::t('app.c2', 'Updated By'),
            'state' => Yii::t('app.c2', 'State'),
            'status' => Yii::t('app.c2', 'Status'),
            'position' => Yii::t('app.c2', 'Position'),
            'created_at' => Yii::t('app.c2', 'Created At'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\AmoebaQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\AmoebaQuery(get_called_class());
    }

    /**
     * setup default values
     **/
    public function loadDefaultValues($skipIfSet = true)
    {
        parent::loadDefaultValues($skipIfSet);
        if ($this->isNewRecord) {
            $this->code = CodeGenerator::getCodeByDate($this, 'ZF');
            $this->seo_code = Yii::$app->security->generateRandomString(10);
        }
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            BlameableBehavior::className()
        ]);
    }

    public function getCreator()
    {
        return $this->hasOne(BeUser::className(), ['id' => 'created_by']);
    }

    public function getUpdater()
    {
        return $this->hasOne(BeUser::className(), ['id' => 'updated_by']);
    }

    public function getAmoebaForms()
    {
        return $this->hasMany(AmoebaForm::className(), ['amoeba_id' => 'id']);
    }

    public function getAmoebaFormItems()
    {
        return $this->hasMany(AmoebaFormItem::className(), ['amoeba_id' => 'id']);
    }

    public function getAmoebaGroups()
    {
        return $this->hasMany(AmoebaGroup::className(), ['amoeba_id' => 'id']);
    }

    public function getParentAmoeba()
    {
        return $this->hasOne(Amoeba::className(), ['id' => 'parent_amoeba_id'])
            ->viaTable('{{%amoeba_group}}', ['children_amoeba_id' => 'id']);
    }

    public function getAmoebaFormJson($withMember = false)
    {

        $root = AmoebaForm::find()->where(['type' => AmoebaFormType::TYPE_C2, 'amoeba_id' => $this->id])->one();
        Yii::info($this->id);
        if ($root) {
            $this->amoebaForms = $this->getAmoebaForms()->all();
            $data = [
                'id' => $root->id,
                'name' => $root->label,
                'type' => $root->type,
                'parent_id' => $root->parent_id,
                'memberList' => $withMember ? $root->getAmoebaFormItemUsersArr() : [],
                'children' => $this->getAmoebaRootChildren($root, $withMember),
            ];


            return Json::encode($data);
            // return json_encode($data);
        }
        return null;
    }

    public function getAmoebaRootChildren($parent, $withMember)
    {
        $rec = [];
        foreach ($this->amoebaForms as $amoebaForm) {
            if ($amoebaForm->parent_id == $parent->id) {
                $children = [];
                if ($this->isHasChildren($amoebaForm)) {
                    $children = $this->getAmoebaRootChildren($amoebaForm, $withMember);
                }
                $rec[] = [
                    'id' => $amoebaForm->id,
                    'name' => $amoebaForm->label,
                    'type' => $amoebaForm->type,
                    'parent_id' => $parent->id,
                    'memberList' => $withMember ? $amoebaForm->getAmoebaFormItemUsersArr() : [],
                    'children' => $children
                ];
            }
        }
        return $rec;
    }

    public function isHasChildren($parent)
    {
        foreach ($this->amoebaForms as $amoebaForm) {
            if ($amoebaForm->parent_id == $parent->id) {
                return true;
            }
        }
        return false;
    }

    public function initAmoebaForm()
    {
        $db = Yii::$app->db->beginTransaction();
//        $c3Model = new AmoebaForm();

//        $c3Model->setAttributes([
//            'amoeba_id' => $this->id,
//            'type' => AmoebaFormType::TYPE_C3,
//            'name' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_C3),
//            'label' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_C3),
//            'parent_id' => 0,
//        ]);
        $c2Model = new AmoebaForm();
        $c2Model->setAttributes([
            'amoeba_id' => $this->id,
            'type' => AmoebaFormType::TYPE_C2,
            'name' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_C2),
            'label' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_C2),
//                'parent_id' => $c3Model->id,
            'parent_id' => 0,
        ]);
        if ($c2Model->save()) {
            $c1Model = new AmoebaForm();
            $c1Model->setAttributes([
                'amoeba_id' => $this->id,
                'type' => AmoebaFormType::TYPE_C1,
                'name' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_C1),
                'label' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_C1),
                'parent_id' => $c2Model->id,
            ]);
            if ($c1Model->save()) {
                for ($i = 0; $i < 3; $i++) {
                    $modelB = new AmoebaForm();
                    $modelB->setAttributes([
                        'amoeba_id' => $this->id,
                        'type' => AmoebaFormType::TYPE_B,
                        'name' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_B),
                        'label' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_B),
                        'parent_id' => $c1Model->id,
                    ]);
                    if ($modelB->save()) {
                        for ($j = 0; $j < 3; $j++) {
                            $modelA = new AmoebaForm();
                            $modelA->setAttributes([
                                'amoeba_id' => $this->id,
                                'type' => AmoebaFormType::TYPE_A,
                                'name' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_A),
                                'label' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_A),
                                'parent_id' => $modelB->id,
                            ]);
                            if ($modelA->save()) {
                                for ($k = 0; $k < 3; $k++) {
                                    $modelP = new AmoebaForm();
                                    $modelP->setAttributes([
                                        'amoeba_id' => $this->id,
                                        'type' => AmoebaFormType::TYPE_P,
                                        'name' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_P),
                                        'label' => AmoebaFormType::getLabel(AmoebaFormType::TYPE_P),
                                        'parent_id' => $modelA->id,
                                    ]);
                                    $modelP->save();
                                }
                            }
                        }
                    }
                }
            }
        }
        $this->updateAttributes(['state' => AmoebaState::TYPE_INIT]);
        $db->commit();
        return true;
    }

}
